//
//  ANVIPRegisterController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/14.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANVIPRegisterController.h"
#import "inputCell.h"
#import "MineInfoFooterView.h"
#import "ANVipPackageSearchController.h"
#import "ANVipStoreController.h"
#import "PaymentDataController.h"
#import "NSCalendar+DateManipulation.h"
#import "WXApiManager.h"

@interface ANVIPRegisterController ()<InputCellTableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MineInfoFooterView *footerView;

@property (nonatomic, strong) UILabel *repaymentDateLab;// 最近还款时间
@property (nonatomic, copy) NSString *repaymentDate;

@property (nonatomic, strong) VipPackageEntity *vipPackageEntity;//会员套餐
@property (nonatomic, strong) VipStoreEntity *shopEntity;//所属商户
@property (nonatomic) int payWay;//支付方式（1全款 2分期）
@property (nonatomic, strong) PaymentDataEntity *paymentEntity;//分期付款
@property (nonatomic, copy) NSString *orgUnitId;//推荐人编号

@end

@implementation ANVIPRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"会员升级";
    
    NSDate *date = [[NSCalendar currentCalendar] dateByAddingMonths:1 toDate:[NSDate date]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    self.repaymentDate = [dateFormatter stringFromDate:date];
    
    WeakSelf
    [WXApiManager sharedManager].resultHandle = ^(NSString * _Nullable orderId) {
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    };
    
}

//orgId：会员id，consumerId：商户，orgUnitId：推荐人编号，memberType：{memberTypeId：会员卡种}，payWay：支付方式（1全款 2分期），stageNum：分期数，recentRepayTime：最近还款时间，dateLimit：开卡年限，dateType:开卡单位（会员套餐列表有返）
- (void)requestDataWithType:(NSInteger)payType
{
    if (!self.shopEntity) {
        [MBProgressHUD showError:@"请选择所属商户"];
        return;
    }
    if (!self.vipPackageEntity) {
        [MBProgressHUD showError:@"请选择会员套餐"];
        return;
    }
    if (!self.payWay) {
        [MBProgressHUD showError:@"请选择付款方式"];
        return;
    }
    else {
        if (self.payWay == 2) {
            if (!self.paymentEntity) {
                [MBProgressHUD showError:@"请选择分期期数"];
                return;
            }
        }
    }
    
//    NSDictionary *memberType = @{@"memberTypeId":self.vipPackageEntity.memberTypeId};
    NSDictionary *member = @{
                           @"orgId":UserUtils.shared.vipId,
                           @"consumerId":self.shopEntity.orgId,
                           @"orgUnitId":StringNone(self.orgUnitId),
                           @"memberTypeId":self.vipPackageEntity.memberTypeId,
                           @"payWay":@(self.payWay),
                           @"stageNum":StringNone(self.paymentEntity.value),
                           @"recentRepayTime":self.repaymentDate,// 下个月的今天
                           @"dateLimit":self.vipPackageEntity.dateLimit,
                           @"dateType":self.vipPackageEntity.dateType,
                           @"firstPayAmount":StringNone(self.vipPackageEntity.firstPayAmount)//首付金额
                           };
    NSDictionary *body = @{
                           @"member":member.yy_modelToJSONString,
                           @"payment":@(payType)
                           };
    [MBProgressHUD showActivityMessage:@"请求中..."];
    [URLManager.shareManager postUrlStr:Api_Upgrade_Vip parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                NSDictionary *data = responseObj[@"data"];
                NSString *orderId = data[@"orderId"];
                NSString *transRecordId = data[@"transRecordId"];
                NSNumber *payState = data[@"payState"];
                if (payState.intValue == 1) {// 直接成功
                    [MBProgressHUD showSuccess:@"支付成功！"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                else {
                    if (payType == 1) {//微信
                        [[WXApiManager sharedManager] wxPayWithOrderId:orderId transRecordId:transRecordId];
                    }
                }
                
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)setupSubViews
{
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    WeakSelf
    self.footerView = [[MineInfoFooterView alloc] initWithFrame:CGRectMake(0, 0, 0, kWidth(100))];
    self.footerView.title = @"提交";
    self.tableView.tableFooterView = self.footerView;
    self.footerView.sureHandler = ^{
        // 升级会员
        [weakSelf sureAction];
    };
}

- (void)sureAction
{
    LLAlertViewController *vc = [[LLAlertViewController alloc] init];
//    vc.actions = @[@"微信支付",@"支付宝"];
//    vc.actionImgs = @[@"pay_wechat",@"pay_alipay"];
    vc.actions = @[@"微信支付"];
    vc.actionImgs = @[@"pay_wechat"];
    vc.actionBlock = ^(NSInteger index, NSString *actionTitle) {
        if (index == 0) {//微信
            [self requestDataWithType:1];
        }
        else {//支付宝
            
        }
    };
    [vc presentBottomViewControllerFromController:self];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3+(self.vipPackageEntity ? 1 : 0);
    }
    return self.payWay == 2 ? 3 : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    inputCell *cell = [tableView dequeueReusableInputCellWithIdentifier:@"inputCell"];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.titleLab.text = @"会员套餐";
            cell.editable = NO;
            cell.text = @"请选择";
            if (self.vipPackageEntity) {
                cell.text = self.vipPackageEntity.typeName;
            }
        }
        if (self.vipPackageEntity && indexPath.row == 1) {
            cell.titleLab.text = @"套餐价格";
            cell.editable = NO;
            cell.text = [NSString stringWithFormat:@"￥%@",StringNone(self.vipPackageEntity.price)];
        }
        if (indexPath.row == 1 + (self.vipPackageEntity ? 1 : 0)) {
            cell.titleLab.text = @"所属商户";
            cell.editable = NO;
            cell.text = @"请选择";
            if (self.shopEntity) {
                cell.text = self.shopEntity.orgName;
            }
        }
        if (indexPath.row == 2 + (self.vipPackageEntity ? 1 : 0)) {
            cell.titleLab.text = @"推荐人";
            cell.editable = YES;
            cell.placeHolderString = @"请输入推荐人编号";
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.titleLab.text = @"付款方式";
            cell.editable = NO;
            cell.text = @"请选择";
            if (self.payWay) {
                if (self.payWay == 1) {
                    cell.text = @"全款";
                }
                if (self.payWay == 2) {
                    cell.text = @"分期";
                }
            }
        }
        if (indexPath.row == 1) {
            cell.titleLab.text = @"首付金额";
            cell.editable = NO;
            cell.text = [NSString stringWithFormat:@"￥%@",String(self.vipPackageEntity.firstPayAmount)];
        }
        if (indexPath.row == 2) {
            cell.titleLab.text = @"分期付款期数";
            cell.editable = NO;
            cell.text = @"请选择";
            if (self.paymentEntity) {
                cell.text = self.paymentEntity.name;
            }
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectTextViewAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //"会员套餐";
            ANVipPackageSearchController *vc = [[ANVipPackageSearchController alloc] init];
            vc.didSelectVipPackage = ^(VipPackageEntity * _Nonnull entity) {
                if (self.vipPackageEntity) {
                    self.vipPackageEntity = entity;
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                    
                }
                else {
                    self.vipPackageEntity = entity;
                    [self.tableView beginUpdates];
                    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                    [self.tableView endUpdates];
                }
                if (self.payWay == 2) {
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
                }
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 1 + (self.vipPackageEntity ? 1 : 0)) {
//            cell.titleLab.text = @"所属商户";
            ANVipStoreController *vc = [[ANVipStoreController alloc] init];
            vc.didSelectStore = ^(VipStoreEntity * _Nonnull entity) {
                self.shopEntity = entity;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            LLAlertViewController *vc = [[LLAlertViewController alloc] init];
            vc.actions = @[@"全款",@"分期"];
            vc.actionBlock = ^(NSInteger index, NSString *actionTitle) {
                if (index == 0) {
                    if (self.payWay == 2) {
                        self.payWay = 1;
                        self.repaymentDateLab.hidden = YES;
                        [self.tableView beginUpdates];
                        [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1], [NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
                        [self.tableView endUpdates];
                    }
                    else {
                        self.payWay = 1;
                    }
                    self.paymentEntity = nil;
                }
                else {
                    if (self.payWay != 2) {
                        self.payWay = 2;
                        [CATransaction begin];
                        [CATransaction setCompletionBlock:^{
                            self.repaymentDateLab.hidden = NO;
                        }];
                        [self.tableView beginUpdates];
                        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1], [NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
                        [self.tableView endUpdates];
                        [CATransaction commit];
                    }
                   
                }
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [vc presentBottomViewControllerFromController:self];
        }
        if (indexPath.row == 2) {
//            cell.titleLab.text = @"分期付款";
            PaymentDataController *vc = [[PaymentDataController alloc] init];
            vc.didSelectPayment = ^(PaymentDataEntity * _Nonnull entity) {
                self.paymentEntity = entity;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}

- (void)tableView:(UITableView *)tableView updataText:(NSString *)text indexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 2 + (self.vipPackageEntity ? 1 : 0)) {// 推荐人
            self.orgUnitId = text;
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        [UIView new];
    }
    UIView *footer = [[UIView alloc] init];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenW-30, 30)];
    title.font = [UIFont systemFontOfSize:12];
    title.textColor = UIColorFromRGB(0x888888);
    title.hidden = YES;
    title.text = [NSString stringWithFormat:@"最近还款时间：%@",self.repaymentDate];
    self.repaymentDateLab = title;
    [footer addSubview:title];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 30;
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 50;
        _tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
